package com.sora.security;

import com.sora.enums.ResultCode;
import com.sora.exception.ApiException;
import com.sora.mapper.UserMapper;
import com.sora.model.entity.UserEntity;
import com.sora.model.vo.ResultVO;
import com.sora.service.impl.UserServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginFilter extends OncePerRequestFilter {

    @Resource
    JwtManager jwtManager;

//    @Resource
//    TokenManager tokenManager;

    @Resource
    UserServiceImpl userService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
//        httpServletResponse.setContentType("application/json;charset=utf-8");
        Claims claims = jwtManager.parse(httpServletRequest.getHeader("Authorization"));
        if (claims != null ){
            String username = claims.getSubject();
            UserDetails userDetail = userService.loadUserByUsername(username);
            Authentication authenticationToken = new UsernamePasswordAuthenticationToken(userDetail, userDetail.getPassword(), userDetail.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
